package com.rem.concurrency.juc.my10ForkJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * 求和计算
 *
 * @author Rem
 * @date 2021-03-10
 */


public class Test {

    public static void main(String[] args) {

        // test1(); //2382
        //test2(); //1057
        test3(); //647
    }


    /**
     * 传统 慢慢累加
     */
    static void test1() {
        long sum = 0L;
        long start = System.currentTimeMillis();
        for (long i = 0L; i <= 100_0000_0000L; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.err.println("结果:" + sum + "  时间:" + (end - start));
    }

    /**
     * 任务拆分
     */
    static void test2() {
        try {
            long start = System.currentTimeMillis();
            ForkJoinPool forkJoinPool = new ForkJoinPool();
            ForkJoinDemo forkJoinDemo = new ForkJoinDemo(0L, 100_0000_0000L);
            ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinDemo);
            long sum = submit.get();
            long end = System.currentTimeMillis();
            System.err.println("结果:" + sum + "  时间:" + (end - start));
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    /**
     * 并行流
     */
    static void test3() {
            long start = System.currentTimeMillis();


        long sum = LongStream.rangeClosed(0L, 100_0000_0000L).parallel().sum();

        long end = System.currentTimeMillis();
            System.err.println("结果:" + sum + "  时间:" + (end - start));
    }



}
